<?php

session_start();

require_once 'database.php';

$db = new DBUnauthConnection();
$header = "Location: http://localhost/Matematrix/index.php";

if (isset($_POST["username"]) && isset($_POST["password"])) {
    $username = $_POST["username"];
    $password = $_POST["password"];
    $password = hash("sha256", $password);
    $id = $db->validate($username, $password);
    if ($id > 0) {
        $_SESSION["authenticated"] = true;
        $_SESSION["nomeUser"] = $db->getName($id);
        $_SESSION["idUser"] = $id;
        $_SESSION["admin"] = false;
        if ($db->isAdmin($id)) {
            $_SESSION["admin"] = true;
        }
    } else {
        $header .= "?invalid=true";
        header($header);
        unset($db);
        exit(0);
    }
    header($header);
    unset($db);
    exit(0);
}
$header .= "?invalid=true";
header($header);
unset($db);
?>
